//设置基地址
import configUrl from "@/common/config";
import { useUserStore } from "@/store/modules/user";

//封装请求
const request = (config: AxiosConfig): any => {
  return new Promise((resolve, reject) => {
    let { url, method, data, params, ...arg } = config;
    method = method ? (method.toUpperCase() as any) : "GET";
    console.log(url);
    data = params ? params : data;
    const userStore = useUserStore();
    const token = userStore.getToken;
    //发起uni请求
    uni.request({
      url: configUrl.hosts + url, //路径
      method,
      header: {
        Authorization: token,
      },
      data,
      ...arg,
      //进入接口成功
      success: (res: any) => {
        if (res.statusCode === 200) {
          let { data } = res;

          console.log(data.code === 0);

          if (data.code === 0) {
            resolve(data);
          } else if (data.code) {
            uni.showToast({
              title: data.msg,
              icon: "none",
              duration: 1000,
            });
            console.log(data.code);
            if (data.code == 401) {
              console.log("重新登录");
              userStore.loginOut();
              uni.navigateTo({ url: "/pages/user/user" });
            }
            reject(data);
          }
        } else {
          uni.showToast({
            title: "服务器错误",
            icon: "none",
            duration: 1000,
          });
          reject(res);
        }
      },
      // 进入接口失败
      fail: (err) => {
        uni.showToast({
          title: "服务器错误",
          icon: "none",
          duration: 1000,
        });
        reject(err);
      },
    });
  });
};

//抛出
export default request;
